import { useRoutes, useNavigate } from 'react-router-dom'
import { useEffect, useState } from 'react'
import defaultRoute from './router'
import { cloneDeep } from 'lodash'
import { getToken } from '@/utils/token'
import NotFound from '@/pages/404'
import { useMenu, getRedirectRoute } from '@/store/useMenu'
import { ConfigProvider, theme } from 'antd'

export default function App() {
  const [route, setRoute] = useState(defaultRoute)

  const { setMenu, getMenu, getKeyMap } = useMenu()

  const whiteList = ['/login']
  const navigate = useNavigate()

  // 初次进去页面判断
  const checkAuthRoute = async path => {
    const hasToken = getToken()

    if (!hasToken) {
      navigate('/login')
      return
    }
    if (whiteList.includes(path)) {
      navigate('/')
      return
    }

    // 如果有token,用户有菜单数据并且白名单中不包含当前路径时，获取当前用户菜单信息
    if (getMenu().length === 0) {
      await setMenu()
      setRoute([
        ...route,
        ...cloneDeep(getMenu()),
        {
          path: '/*',
          element: <NotFound />
        }
      ])
    }
    // 当输入地址不全时，判断重定向路由，默认第一个
    const routeItem = getKeyMap()[path]
    if (routeItem && routeItem?.children?.length > 0) {
      navigate(getRedirectRoute(path, routeItem))
    }
  }

  useEffect(() => {
    checkAuthRoute(location.pathname)
  }, [location.pathname])

  return <ConfigProvider>{useRoutes(route)}</ConfigProvider>
}
